package com.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Description JWT工具类
 * @date 2023/6/16 17:22
 * @author Huangjunjie
 * @since JDK 1.8
*/
//@Component
public class JwtUtil2 {

    // 加密解密时的密钥，用于生成key  - 对称加密
    public static final String JWT_KEY = "BZ2023";

    /**
     * 生成加密后的秘钥 secretKey
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil2.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 创建JWT (JSON Web Token)
     *
     * @param id        JWT ID，用作唯一标识
     * @param subject   JWT 主题，代表这个JWT的所有人
     * @param ttlMillis JWT 的有效期时间（毫秒）
     * @return 生成的JWT
     */
    public static String createJWT(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解析JWT，获取其中的Claims
     *
     * @param jwt 要解析的JWT
     * @return 解析后的Claims
     */
    public static Claims parseJWT(String jwt) {
        SecretKey key = generalKey();
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
        Claims claims = parseJWT(
                "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIwYmYwYThlNy0yZDcwLTQ2ZDQtYjlmZi05NTkwODYyNTU3NDYiLCJpYXQiOjE2OTI1NzkzNzQsInN1YiI6IjQxNjM3NjE2NzYxMjgwOTIxNiIsImV4cCI6MTY5MjYwMDk3NH0.2kjDRXYsyFVUnjXmygP7qLMqR2FFfy5SoRdmrAuP6AM");
        System.out.println(claims.getSubject());
    }
    public static boolean validatePassword(String password) {
        // 至少包含三种（大写字母、小写字母、数字、特殊符号）字符的正则表达式
        String pattern = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$";
        Pattern regexPattern = Pattern.compile(pattern);
        Matcher matcher = regexPattern.matcher(password);

        return matcher.matches();
    }
}